﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using Facade;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;


namespace IronOne.SalesOne.SalesOneWeb.NeedsAnalysis
{
    public partial class SearchNeedsAnalysis : SOSecurityPage, IDataPage,IntTest
    {
        //, IntTest
        private int pageNo = 1;
        List<IDType> idtypes;
        CodeFacade idType = new CodeFacade();
        List<BusinessObjects.NeedsAnalysis> customers;
        StructureFacade facade;
        public List<Branch> brnch;
        public List<SalesOneUnit> un;
        public List<string> so;
        int userType;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                facade = new StructureFacade();

                //ValidateUserCredentials(Request.Url.LocalPath);


                
                if (!IsPostBack)
                {
                    FillDropdownIDType("IDType");
                    SearchUserType("userId");
                }

                //string postCause = this.Page.Request.Params.Get("__EVENTTARGET");

                //if (postCause == null)
                //{
                //    if (Session["p"] != null)
                //    {
                //        Search(int.Parse(Session["p"].ToString()));
                //        Session.Remove("p");
                //    }
                    
                //}
            }
            catch (Exception)
            {

            }
            
        }


        #region IDataPage Members

        public void Create()
        {


        }

        public void View()
        {
            try
            {
                if (Session["naRow"] == null)
                {
                    Session["naRow"] = ((GridViewRow)Session["firstRow"]);
                    Session.Remove("firstRow");
                }

                GridViewRow rw = (GridViewRow)Session["naRow"];
                //Session.Remove("naRow");
                Response.Redirect("~/ContactManagement/ProspectDetails.aspx?id=" + rw.Cells[6].Text + "&t=v&nid=" + rw.Cells[4].Text);
            }
            catch (Exception)
            {

            }
            
        }

        public void Update()
        {
            try
            {
                if (Session["naRow"] == null)
                {
                    Session["naRow"] = ((GridViewRow)Session["firstRow"]);
                    Session.Remove("firstRow");
                }

                GridViewRow rw = (GridViewRow)Session["naRow"];
                //Session.Remove("naRow");
                Response.Redirect("~/ContactManagement/ProspectDetails.aspx?id=" + rw.Cells[6].Text + "&t=u&nid=" + rw.Cells[3].Text);
            }
            catch (Exception)
            {

            }
            


        }
        public void Delete()
        {


        }

        public void Cancel()
        {

        }

        #endregion

        public void SearchUserType(String userId)
        {
            try
            {
                facade = new StructureFacade();
                User user = facade.GetUser(User.Identity.Name);
                UserInformation info = facade.GetUserInformation(User.Identity.Name);
                userType = info.UserType;



                bool flag = false;

                if (userType == 4)
                {
                    populateSOCodes(facade.GetSOsInUnit(user.NodeId));
                    flag = true;
                }

                if (flag == true)
                {
                    ListItem ls = new ListItem();
                    ls.Text = info.UnitName;
                    ls.Value = info.UnitId.ToString();

                    ddlUnit.Items.Add(ls);
                    ddlUnit.SelectedIndex = ddlUnit.Items.Count - 1;

                    ddlUnit.Enabled = false;
                }
                else if (userType == 3)
                {
                    populateUnits(facade.GetUnitsForBranch(user.NodeId));
                    addDefaultItem(ddlSoCode);
                    flag = true;
                }

                if (flag == true)
                {
                    ListItem ls = new ListItem();
                    ls.Text = info.BranchName;
                    ls.Value = info.BranchId.ToString();
                    ddlBranch.Items.Add(ls);
                    ddlBranch.SelectedIndex = ddlBranch.Items.Count - 1;

                    ddlBranch.Enabled = false;
                }
                else if (userType == 2)
                {
                    populateBranches(facade.GetBranchesForGroup(user.NodeId));
                    addDefaultItem(ddlUnit);
                    addDefaultItem(ddlSoCode);

                    flag = true;
                }

                if (userType == 1)
                {
                    populateBranches(facade.GetBranches("BranchName ASC"));
                    addDefaultItem(ddlUnit);
                    addDefaultItem(ddlSoCode);
                }
            }
            catch (Exception)
            {

            }
            
        }

        private void populateBranches(List<Branch> branches)
        {
            try
            {
                ddlBranch.DataSource = branches;
                ddlBranch.DataTextField = "BranchName";
                ddlBranch.DataValueField = "BranchID";
                ddlBranch.DataBind();

                addDefaultItem(ddlBranch);
            }
            catch (Exception)
            {

            }

        }

        private void populateUnits(List<SalesOneUnit> units)
        {
            try
            {
                ddlUnit.DataSource = units;
                ddlUnit.DataTextField = "Name";
                ddlUnit.DataValueField = "UnitID";
                ddlUnit.DataBind();

                addDefaultItem(ddlUnit);
            }
            catch (Exception)
            {

            }

        }

        private void populateSOCodes(List<string> users)
        {
            try
            {
                ddlSoCode.Items.Clear();
                foreach (string str in users)
                {
                    ddlSoCode.Items.Add(str);
                }
                addDefaultItem(ddlSoCode);
            }
            catch (Exception)
            {

            }
           
        }

        private void addDefaultItem(DropDownList ddl)
        {
            ListItem newItem = new ListItem("Select...");
            ddl.Items.Insert(0, newItem);
        }

        private void SetOnlyDefault(DropDownList ddl)
        {
            ListItem newItem = new ListItem("Select...");
            ddl.Items.Insert(0, newItem);
            ddl.DataBind();

        }

        protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ////String IDNumber = txtIdNo.Text;
            //String IDType = ddlIdType.SelectedValue;
            ////Search(ID, IDType);
            //Search((txtIdNo.Text), IDType);
            pageNo = 1;
            Search(1);
        }

        public void Search(int pageNo)
        {
            try
            {
                CustomerFacade cFac = new CustomerFacade();
                int branchId;
                int unitId;
                string soCode = string.Empty;
                string idNo = txtIdNo.Text;
                string idType = string.Empty;
                string name = txtName.Text;
                string prospId = txtProspectId.Text;
                int needAnNo = 0;

                Session["p"] = pageNo.ToString();

                if (pageNo == 1)
                {
                    UCGrid1.SetText("1");
                }

                if (ddlIdType.SelectedValue != "-1")
                {
                    idType = ddlIdType.SelectedValue;
                }

                if (!string.IsNullOrEmpty(txtNeedsAnalysisNo.Text))
                {
                    needAnNo = Convert.ToInt32(txtNeedsAnalysisNo.Text);
                }

                if (ddlBranch.SelectedValue != "Select...")
                {
                    branchId = int.Parse(ddlBranch.SelectedValue);
                    Branch brs = facade.GetBranch(branchId);
                    brnch = new List<Branch>();
                    brnch.Add(brs);
                }

                if (ddlUnit.SelectedValue != "Select..." && ddlUnit.SelectedIndex != -1)
                {
                    unitId = int.Parse(ddlUnit.SelectedValue);
                    SalesOneUnit sun = facade.GetUnit(unitId);
                    un = new List<SalesOneUnit>();
                    un.Add(sun);
                }

                if (ddlSoCode.SelectedValue != "Select..." && ddlSoCode.Items.Count > 0)
                {
                    soCode = ddlSoCode.SelectedValue;
                    so = new List<string>();
                    so.Add(soCode);
                }


                NeedAnalysisSearch nas = new NeedAnalysisSearch();
                nas.BranchName = brnch;
                nas.UnitName = un;
                nas.So = so;
                nas.IdNo = idNo;
                nas.IdType = idType;
                nas.Name = name;
                nas.ProspectId = prospId;
                if (needAnNo != 0)
                {
                    nas.NeedAnalysisNo = needAnNo;
                }

                bool flag = true;

                if (!string.IsNullOrEmpty(name) && (brnch == null || un == null))
                {
                    flag = false;
                    MassageSummery("IIS518");
                }

                if (!string.IsNullOrEmpty(idNo) || !string.IsNullOrEmpty(idType))
                {
                    if (!(!string.IsNullOrEmpty(idNo) && !string.IsNullOrEmpty(idType)))
                    {
                        flag = false;
                        MassageSummery("IIS511");
                    }

                }


                if (flag == true)
                {
                    List<IronOne.SalesOne.BusinessObjects.NeedsAnalysis> needList = cFac.GetNeedAnalysisCustomers(nas, pageNo);
                    if (needList.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                    {
                        UCGrid1.IsLastPage = (cFac.GetNeedAnalysisCustomers(nas, pageNo + 1)).Count > 0 ? false : true;
                    }

                    if (needList == null || needList.Count == 0)
                    {
                        UCGridButtons1.Visible = false;
                        MassageSummery("IIS504");
                    }
                    else
                    {
                        UCGridButtons1.SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));
                        UCGridButtons1.Visible = true;
                    }

                    int[] arr = { 1, 2, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66 };

                    UCGrid1.styleList = new List<GridViewStyle> {
                new GridViewStyle{
                    ColumnId = "IdNo",
                    ColumnHeader = "ID No",
                    ColumnWidth = 130 },
                new GridViewStyle{
                    ColumnId = "NeedAnalysisNo",
                    ColumnHeader = "Needs Analysis No",
                    ColumnWidth = 130},                
                new GridViewStyle{
                    ColumnId = "SoCode",
                    ColumnHeader = "SO Cd",
                    ColumnWidth = 100},
                new GridViewStyle{
                    ColumnId = "ProspectId",
                    ColumnHeader = "Prospect Id",
                    ColumnWidth = 130},
                new GridViewStyle{
                    ColumnId = "CreatedDate",
                    ColumnHeader = "Created Date",
                    ColumnWidth = 130}
                
            };





                    UCGrid1.SetDataSource(needList, arr);

                }
            }
            catch (Exception)
            {

            }
            

        }

        public void FillDropdownIDType(String idtype)
        {
            try
            {
                List<IDType> idtypes = idType.GetIDTypes("BenefitName ASC");
                IDType idt = new IDType();
                idt.CodeId = -1;
                idt.Description = "Select...";
                idtypes.Insert(0, idt);

                ddlIdType.DataSource = idtypes;
                ddlIdType.DataTextField = "Description";
                ddlIdType.DataValueField = "CodeId";
                ddlIdType.DataBind();
            }
            catch (Exception)
            {

            }
            

        }

        #region IDataPage Members - rbn session


        public void GetId(GridViewRow row)
        {
            Session["naRow"] = row;
        }

        #endregion

        protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            try
            {
                if (ddlBranch.SelectedIndex > 0)
                {
                    populateUnits(facade.GetUnitsInBranch(int.Parse(ddlBranch.SelectedValue)));
                    ddlUnit.SelectedIndex = 0;
                    ddlSoCode.SelectedIndex = 0;
                }
                else
                {
                    List<SalesOneUnit> units = new List<SalesOneUnit>();
                    populateUnits(units);

                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception ex)
            {

            }
        }

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlUnit.SelectedIndex > 0)
                {
                    populateSOCodes(facade.GetSOsInUnit(int.Parse(ddlUnit.SelectedValue)));
                }
                else
                {
                    List<string> us = new List<string>();
                    populateSOCodes(us);
                }
            }
            catch (Exception ex)
            {

            }
        }

        protected void ddlSoCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddlSoCode.SelectedIndex > 0)
            //{
            //    btnSearch.Enabled = true;
            //}
        }


        #region IntTest Members

        public void Next()
        {
            try
            {
                if (UCGrid1.GetText() != "1")
                {
                    pageNo = Convert.ToInt32(UCGrid1.GetText()) + 1;
                    UCGrid1.SetText(pageNo.ToString());

                }
                else
                {
                    pageNo = 2;
                    UCGrid1.SetText("2");

                }

                Search(pageNo);
            }
            catch (Exception)
            {

            }
        }

        public void Previous()
        {
            try
            {
                if (UCGrid1.GetText() != "1")
                {
                    pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
                    UCGrid1.SetText(pageNo.ToString());

                    Search(pageNo);
                }
            }
            catch (Exception)
            {

            }
        }

        public void Go()
        {
            int p = int.Parse(UCGrid1.GetText());
            if (p != 0)
            {
                try
                {
                    Search(p);
                    pageNo = p;
                }
                catch (Exception ex)
                {

                    //Response.Write(ex.Message);
                }


            }
        }

        #endregion
    }
}
